﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Zadanie3
{
    public partial class Form1 : Form
    {
        TollHouses tollHouses = new TollHouses();
        private Thread[] runningNorthbound, runningSouthbound;
        private int numThreads = 10;

        private void PassingBridgeNorthbound()
        {
            while (true)
            {
                Random rng = new Random();
                tollHouses.Enter(TollHouses.Direction.NORTHBOUND);
                Thread.Sleep(500 + rng.Next(2000));
                tollHouses.Leave(TollHouses.Direction.NORTHBOUND);
                Thread.Sleep(1000 + rng.Next(4000));
            }
        }

        private void PassingBridgeSouthbound()
        {
            while (true)
            {
                Random rng = new Random();
                tollHouses.Enter(TollHouses.Direction.SOUTHBOUND);
                Thread.Sleep(500 + rng.Next(2000));
                tollHouses.Leave(TollHouses.Direction.SOUTHBOUND);
                Thread.Sleep(1000 + rng.Next(4000));
            }
        }

        private void BridgeChanged()
        {
            Invoke((MethodInvoker) delegate()
            {
                northboundLabel.Text = "northbound: " + tollHouses.Northbound.ToString();
                southboundLabel.Text = "southbound: " + tollHouses.Southbound.ToString();
            });
        }

        public Form1()
        {
            InitializeComponent();

            runningNorthbound = new Thread[numThreads];
            runningSouthbound = new Thread[numThreads];
            for (int i = 0; i < numThreads; i++)
            {
                runningNorthbound[i] = new Thread(new ThreadStart(PassingBridgeNorthbound));
                runningNorthbound[i].Start();

                runningSouthbound[i] = new Thread(new ThreadStart(PassingBridgeSouthbound));
                runningSouthbound[i].Start();
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            for (int i = 0; i < numThreads; i++)
            {
                runningNorthbound[i].Abort();
                runningSouthbound[i].Abort();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tollHouses.Changed += new ChangedEventHandler(BridgeChanged);
        }
    }
}
